package com.yunqiao.service.api.impl;

import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunqiao.common.config.SysConfig;
import com.yunqiao.common.exception.CustomApiException;
import com.yunqiao.common.utils.PageUtils;
import com.yunqiao.common.utils.Query;
import com.yunqiao.common.utils.SmsUtils;
import com.yunqiao.service.api.SysSmscodeService;
import com.yunqiao.service.api.entity.SysSmscodeEntity;
import com.yunqiao.service.api.mapper.SysSmscodeMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;


@Service("sysSmscodeService")
public class SysSmscodeServiceImpl extends ServiceImpl<SysSmscodeMapper, SysSmscodeEntity> implements SysSmscodeService {

    @Resource
    private SysSmscodeMapper sysSmscodeMapper;
    @Resource
    private TimedCache<String, String> timedCache;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //各种查询条件的过滤,在此进行
        QueryWrapper<SysSmscodeEntity> queryWrapper = new QueryWrapper<>();

        IPage<SysSmscodeEntity> page = this.page(new Query<SysSmscodeEntity>(params).getPage(),queryWrapper);
        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String sendSms(String phone) throws Exception {
        //获取最近的一条数据
        SysSmscodeEntity sysSmscodeEntity = sysSmscodeMapper.selectOne(new QueryWrapper<SysSmscodeEntity>()
            .eq("phone", phone)
            .apply(true, "created_at in (select max(created_at) from sys_smscode where phone = '"+phone+"')"));
        if (sysSmscodeEntity != null) {
            if ((DateUtil.date().getTime() - sysSmscodeEntity.getCreatedAt().getTime())/1000 < 60) {
                throw new CustomApiException("您刚发过验证码，请在60秒后再次发送");
            }
            //删除之前的短信
            this.sysSmscodeMapper.delete(new UpdateWrapper<SysSmscodeEntity>().eq("phone", phone));
        }

        String code = RandomUtil.randomNumbers(6);
        sysSmscodeEntity = new SysSmscodeEntity();
        sysSmscodeEntity.setPhone(phone);
        sysSmscodeEntity.setSmscode(code);
        timedCache.put(phone,code);
        sysSmscodeEntity.setCreatedAt(new Date());
        sysSmscodeMapper.insert(sysSmscodeEntity);
        if(SysConfig.host.indexOf("wx.hzjrsy")!=-1||SysConfig.host.indexOf("app.hzjrsy")!=-1){
            SmsUtils.send(phone, SmsUtils.TemplateEnum.TEMPLATE_4, code);
        }
        System.out.println(code+"验证码");
        return code;
    }

}
